<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise发送AJAX</title>
  </head>
  <button>AJAX</button>

  <body></body>

  <script>
    //重要  重要  重要
    let btn = document.querySelector("button");

    btn.onclick = function () {
      //实例化 promise 对象
      let p = new Promise((resolve, reject) => {
        //
        let xhr = new XMLHttpRequest();
        //
        xhr.responseType = "json";
        //
        xhr.open("get", "http://api.xiaohigh.com/duanzi");
        //
        xhr.send();
        //
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            //响应状态码
            if(xhr.status >= 200 && xhr.status < 300){
                //成功的情况
                resolve(xhr.response);//响应体为成功的结果值
            }else{
                //失败的情况
                reject(xhr.status); // 响应状态码作为失败的结果值
            }
          }
        };
      });
    
      //处理成功或失败的结果值
      p.then(body => {
        console.log(body);
      }, status => {
        console.warn('请求失败, 失败的响应状态码为' + status);
      })
    };
  </script>
</html>
